package com.study.lxy.springcloud.uclient.service.impl;

import com.study.lxy.springcloud.common.exception.BusiException;
import com.study.lxy.springcloud.common.utils.PasswordUtil;
import com.study.lxy.springcloud.common.utils.RedisUtils;
import com.study.lxy.springcloud.common.utils.UUIDUtils;
import com.study.lxy.springcloud.uclient.constants.RespCodeEnum;
import com.study.lxy.springcloud.uclient.dao.ClientUserDao;
import com.study.lxy.springcloud.uclient.entity.ClientUser;
import com.study.lxy.springcloud.uclient.service.UserLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Component
public class UserLoginServiceImpl implements UserLoginService {
    private static final Logger logger = LoggerFactory.getLogger(UserLoginServiceImpl.class);
    @Autowired
    private ClientUserDao clientUserDao;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public void loginOn(ClientUser user) {
        logger.info("loging user = {}",user);
        validateParm(user);
        ClientUser queryUser = new ClientUser();
        queryUser.setMobile(user.getMobile());
        List<ClientUser> userList = clientUserDao.queryUser(queryUser);
        if(CollectionUtils.isEmpty(userList)){
            throw new BusiException(RespCodeEnum.USER_OR_PWD_INVILD);
        }
        ClientUser resultUser = userList.get(0);
        if(!PasswordUtil.verifyPassword(user.getPassword(),resultUser.getSalt(),resultUser.getPassword())){
            throw new BusiException(RespCodeEnum.USER_OR_PWD_INVILD);
        }
        // 待补充，将登陆状态缓存到redis中，并在cookie中返回一个sessionId
        String sessionId = UUIDUtils.getUUID();
        Cookie cookie = new Cookie("SESSION_ID",sessionId);
        cookie.setMaxAge(15 * 60);
        response.addCookie(cookie);
        redisUtils.set("SESSION_ID:" + sessionId,user,900);
        logger.info("login successful,session id = {}",sessionId);
    }

    @Override
    public void loginOut() {
        ClientUser user = (ClientUser)redisUtils.get("SESSION_ID:" + getSessionId());
        logger.info("clientUser={}",user);
        redisUtils.del("SESSION_ID:" + getSessionId());
        Cookie cookie = new Cookie("SESSION_ID",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        logger.info("loginOut successful,session id = {}",getSessionId());
    }

    private void validateParm(ClientUser user){

        if(StringUtils.isEmpty(user.getMobile())){
            throw new BusiException(RespCodeEnum.PARM_INVILD,"手机号必输");
        }
        if(StringUtils.isEmpty(user.getPassword())){
            throw new BusiException(RespCodeEnum.PARM_INVILD,"密码必输");
        }

    }

    private String getSessionId(){
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if("SESSION_ID".equals(cookie.getName())){
                return cookie.getValue();
            }
        }
        return null;
    }
}
